package com.hxy.controller;

import com.hxy.entity.Type;
import com.sun.deploy.util.ArrayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.util.ArrayUtils;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class PrepostController {

    @RequestMapping("m1")
    public String m1() {
        return "m1";
    }

    // 进入方法前执行验证
    // hasRole：是否有角色
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping("m2")
    public String m2() {
        log.info(">>>>>>>>>进入m2方法");
        return "m2";
    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROlE_TEST')")
    @RequestMapping("m3")
    public String m3() {
        return "m3";
    }

    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_TEST')")
    @RequestMapping("m4")
    public String m4() {
        return "m4";
    }

    // 方法执行完成返回接过前执行验证
    @PostAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping("m5")
    public String m5() {
        log.info(">>>>>>>>进入方法m5");
        return "m5";
    }

    // 有select权限可以访问
    @PreAuthorize("hasAuthority('select')")
    @RequestMapping("m6")
    public String m6() {
        return "m6";
    }

    @PreAuthorize("hasAuthority('add')")
    @RequestMapping("m7")
    public String m7() {
        return "m7";
    }

    // principal：认证主体
    @PreAuthorize("principal.uname.equals('zhangsan')")
    @RequestMapping("m8")
    public String m8() {
        return "m8";
    }


    // authentication认证信息
    // #参数名获取参数信息
    @PreAuthorize(" #uname.equals('aaa') ")
    @RequestMapping("m9")
    public String m9(String uname) {
        return "m9";
    }

    // returnObject:返回值
    @PostAuthorize("returnObject.equals('ok')")
    @RequestMapping("m10")
    public String m10(String msg) {
        return msg;
    }

    // 方法执行前调用，过滤数据
    // 过滤不满足条件的参数
    @PreFilter(filterTarget = "types", value = "filterObject.tid%2==0")
    @RequestMapping("m11")
    public String m11(@RequestBody List<Type> types) {
        System.out.println(types.toString());
        return "ok";
    }

    // 方法执行后调用，过滤数据
    // 过滤不满足条件的返回值
    @PostFilter(value = "returnObject.tid%2==0")
    @RequestMapping("m12")
    public List<Type> m12() {
        ArrayList<Type> list = new ArrayList<>();
        list.add(new Type(1));
        list.add(new Type(2));
        list.add(new Type(3));
        list.add(new Type(4));
        return list;
    }
}
